const userModel = require('../models/user');
const ctrlObject = {
	//分页查询用户
	getUserByPage: async (req, res) => {
		try {
			const { page, size } = req.query;
			const limit = parseInt(size);
			const skip = (page - 1) * limit;
			const users = await userModel.find().limit(limit).skip(skip);
			const total = await userModel.countDocuments();
			res.status(200).json({ users, total });
		} catch (error) {
			res.status(500).json(error);
		}
	},

	createUser: async (req, res) => {
		try {
			const user = new userModel(req.body);
			await user.save();
			res.status(200).json(user);
		} catch (error) {
			res.status(500).json(error);
		}
	},
	getAllUsers: async (req, res) => {
		try {
			const users = await userModel.find();
			res.status(200).json(users);
		} catch (error) {
			res.status(500).json(error);
		}
	},
	getUserById: async (req, res) => {
		try {
			const user = await userModel.findById(req.params.id);
			res.status(200).json(user);
		} catch (error) {
			res.status(500).json(error);
		}
	},
	updateUser: async (req, res) => {
		try {
			const user = await userModel.findByIdAndUpdate(req.params.id, req.body, { new: true });
			res.status(200).json(user);
		} catch (error) {
			res.status(500).json(error);
		}
	},
	deleteUser: async (req, res) => {
		try {
			const user = await userModel.findByIdAndDelete(req.params.id);
			res.status(200).json(user);
		} catch (error) {
			res.status(500).json(error);
		}
	}
}
module.exports = ctrlObject;